package myschool.web;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;
import myschool.entity.Grade;
import myschool.entity.Page;
import myschool.entity.Student;
import myschool.entity.Subject;
import myschool.service.ExamService;
import myschool.service.GradeService;
import myschool.service.StudentService;
import myschool.service.SubjectService;
import myschool.util.StrUtil;
import myschool.vo.Result;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.imageio.ImageIO;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.UUID;

//通用的servlet
//login.do
//update.do
//admin/login.do
@WebServlet(name = "MainServlet", value = "*.do")
public class MainServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {
        Result result=null;
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
//        PrintWriter out = response.getWriter();
//        out.print("<h1>");
//        out.print("context-path:" + request.getContextPath());
//        out.print("</h1>");
//        out.print("<h1>");
//        out.print("servlet-path:" + request.getServletPath());
//        out.print("</h1>");
//        out.print("<h1>");
//        out.print("url:" + request.getRequestURL());
//        out.print("</h1>");
//        out.print("<h1>");
//        out.print("uri:" + request.getRequestURI());
//        out.print("</h1>");
//        out.print("<h1>");
//        out.print("method:" + request.getMethod());
//        out.print("</h1>");
//        out.print("<h1>");
//        out.print("Query-String:" + request.getQueryString());
//        out.print("</h1>");
//        out.print("<h1>");
//        out.print("pathinfo:" + request.getPathInfo());
//        out.print("</h1>");
//        String path=request.getServletPath();
//        path=path.substring(1,path.length()-3);
//        out.print("<h2 style='color:red'>");
//        if(path.equals("login")){
//            out.print("你在请求登录操作");
//        }else if(path.equals("update")){
//            out.print("你在请求修改操作");
//        }else if(path.equals("delete")){
//            out.print("你在请求删除操作");
//        }else if(path.equals("add")){
//            out.print("你在请求增加操作");
//
//        }else{
//            out.print("未知操作");
//        }
//        out.print("</h2>");
        String path = request.getServletPath();
        path = path.substring(1, path.length() - 3);

        try {
            Method method = this.getClass().getDeclaredMethod(path, HttpServletResponse.class,
                    HttpServletRequest.class);
            Object invoke = method.invoke(this, response, request);
            System.out.println("结果是：" + invoke);
            if (invoke == null)
                return;
            if (invoke instanceof String) {///是重定向的地址
                request.getRequestDispatcher((String) invoke).forward(request, response);
                return;
            }

            String s2 = JSON.toJSONString(invoke, "yyyy-MM-dd", JSONWriter.Feature.NullAsDefaultValue);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(s2);
            return;
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
            //>response.getWriter().print("没有这个请求：" + path);
            result=Result.error("没有这个请求：" + path);
        } catch (Exception e) {
            e.printStackTrace();
            //>response.getWriter().print("请求出错" + e);
            result=Result.error("请求出错" + e);
        }
        if(result!=null){
            String s2 = JSON.toJSONString(result, "yyyy-MM-dd", JSONWriter.Feature.NullAsDefaultValue);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(s2);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {
        this.doPost(request, response);
    }

//    @Override
//    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        this.doPost(req, resp);
//    }
//
//    @Override
//    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        this.doPost(req, resp);
//    }

    //课程分页
    public void subject(HttpServletResponse response, HttpServletRequest request) throws ServletException,
            IOException {
        int pageNo = StrUtil.toInt(request.getParameter("pageNo"), 1);
        pageNo = pageNo < 1 ? 1 : pageNo;
        String sname = StrUtil.toStr(request.getParameter("subjectname"));

        Page<Subject> p = SubjectService.ME.page(pageNo, Page.PAGESIZE, sname);

        request.setAttribute("sname", sname);
        request.setAttribute("p", p);
        request.getRequestDispatcher("/WEB-INF/jsps/subject.jsp").forward(request, response);
    }

    public void delsubject(HttpServletResponse response, HttpServletRequest request) throws ServletException,
            IOException {
        int del = SubjectService.ME.del(Long.parseLong(request.getParameter("id")));
        //response.sendRedirect("subject.do");
        //response.getWriter().print("<script>alert('"+(del>0?"删除成功":"删除失败")+"');window.location='subject.do';
        // </script>");
        response.getWriter().print("<script>document.write('" + (del > 0 ? "删除成功" : "删除失败") + "');window.setTimeout(" +
                "()=>{window.location='subject.do';},2000);</script>");
    }

    public void toAddSubject(HttpServletResponse response, HttpServletRequest request) throws ServletException,
            IOException {
        request.setAttribute("grades", GradeService.ME.page(1, 1000).getData());

        request.getRequestDispatcher("/WEB-INF/jsps/addSubject.jsp").forward(request, response);
    }

    public void checkSubjectName(HttpServletResponse response, HttpServletRequest request) throws ServletException,
            IOException {
        String name = request.getParameter("subjectname");
        boolean repeat = SubjectService.ME.checkNameRepeat(name);
        //response.getWriter().println(repeat); 不能 ln
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        response.getWriter().print(repeat);
    }

    public void showScore(HttpServletResponse response, HttpServletRequest request) throws ServletException,
            IOException {
        int pageNo = StrUtil.toInt(request.getParameter("pageNo"), 1);
        Long stno = StrUtil.toLong(request.getParameter("stuno"), 0);
        //request.setAttribute("student", StudentService.ME);
        String subname = request.getParameter("subjectname");
        Date start = StrUtil.toDate(request.getParameter("start"));
        Date end = StrUtil.toDate(request.getParameter("end"));
        request.setAttribute("stuno", stno);
        request.setAttribute("subjectname", subname);
        request.setAttribute("start", start);
        request.setAttribute("end", end);

        request.setAttribute("p", ExamService.ME.page(pageNo, Page.PAGESIZE / 3, stno, subname, start, end));
        request.getRequestDispatcher("/WEB-INF/jsps/stuScore.jsp").forward(request, response);
    }

    public Page<Student> studentsAjax(HttpServletResponse response, HttpServletRequest request) throws ServletException,
            IOException {
        String sname = StrUtil.toStr(request.getParameter("sname"));
        String tel = StrUtil.toStr(request.getParameter("tel"));
        String QQ = StrUtil.toStr(request.getParameter("QQ"));
        int pageNo = StrUtil.toInt(request.getParameter("page"), 1);
        int pageSize = StrUtil.toInt(request.getParameter("limit"), Page.PAGESIZE);

        Date end = StrUtil.toDate(request.getParameter("end"));
        Date start = StrUtil.toDate(request.getParameter("start"));
        Page<Student> p = StudentService.ME.page(pageNo, pageSize, sname, tel, QQ, start, end);
        return p;
//        String s2= JSON.toJSONString(p,"yyyy/MM/dd", JSONWriter.Feature
// .NullAsDefaultValue);
////
////        //改一下响应的格式，为json
////        response.setContentType("application/json;charset=utf-8");
////        response.getWriter().print(s2);
    }

    //    public void delStudent(HttpServletResponse response, HttpServletRequest request) throws ServletException,
//            IOException {
//        Long stuno = Long.parseLong(request.getParameter("stuno"));
//        int r = StudentService.ME.del(stuno);
//        response.setContentType("application/json;charset=utf-8");
//        response.getWriter().print(r);
//    }
    public Result delStudent(HttpServletResponse response, HttpServletRequest request) throws ServletException,
            IOException {
        Long stuno = Long.parseLong(request.getParameter("stuno"));
        int r = StudentService.ME.del(stuno);
        return r > 0 ? Result.success("删除成功") : Result.error("删除失败");
    }

    public Result upload(HttpServletResponse response, HttpServletRequest request) throws ServletException,
            IOException {
        //暂存目录，java.io.tempdir
        DiskFileItemFactory df = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(df);
        //中文问题
        upload.setHeaderEncoding("utf-8");
        try {
            List<FileItem> fileItems = upload.parseRequest(request);
            FileItem fi = fileItems.get(0);
            if (fi.getSize() < 1) {
                return Result.error("没有找到图片");
            }
            //需要换个名字，保留后缀
            String oldName = fi.getName();
            String houzhui = oldName.substring(oldName.lastIndexOf('.'));
            String newName = UUID.randomUUID() + houzhui;
            ServletContext application = super.getServletContext();
            String path0 = application.getRealPath("img");
            File path = new File(path0);
            if (!path.exists())
                path.mkdirs();
            fi.write(new File(path, newName));
            return Result.success("img/" + newName, "上传成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("错误：" + e);
        }

        ///return Result.error("");
    }

        public Result updStudent(HttpServletResponse response, HttpServletRequest request) throws ServletException,
            IOException {
        Student student = new Student();
        //暂存目录，java.io.tempdir
        DiskFileItemFactory df = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(df);
        //中文问题
        upload.setHeaderEncoding("utf-8");

        try {
            List<FileItem> fileItems = upload.parseRequest(request);
            //文件域和表单域单独处理
            PrintWriter out = response.getWriter();
            for (FileItem fi : fileItems) {
                if (fi.isFormField()) {//表单域
                    if (fi.getFieldName().equals("stuno")) {
                        student.setStuno(Long.parseLong(fi.getString("utf-8")));
                    } else if (fi.getFieldName().equals("sname")) {
                        student.setSname(fi.getString("utf-8"));
                    } else if (fi.getFieldName().equals("sex")) {
                        student.setSex(fi.getString("utf-8"));
                    } else if (fi.getFieldName().equals("telephone")) {
                        student.setTelephone(fi.getString("utf-8"));
                    } else if (fi.getFieldName().equals("qq")) {
                        student.setQQ(fi.getString("utf-8"));
                    } else if (fi.getFieldName().equals("wechat")) {
                        student.setWechat(fi.getString("utf-8"));
                    } else if (fi.getFieldName().equals("gradeid")) {
                        student.setGradeid(Long.parseLong(fi.getString("utf-8")));
                    } else if (fi.getFieldName().equals("enterdate")) {
                        student.setEnterdate(StrUtil.toDate(fi.getString("utf-8")));
                    } else if (fi.getFieldName().equals("birthday")) {
                        student.setBirthday(StrUtil.toDate(fi.getString("utf-8")));
                    } else if (fi.getFieldName().equals("fromcity")) {
                        student.setFromcity(fi.getString("utf-8"));
                    } else if (fi.getFieldName().equals("address")) {
                        student.setAddress(fi.getString("utf-8"));
                    } else if (fi.getFieldName().equals("password")) {
                        student.setPassword(fi.getString("utf-8"));
                    }
                    continue;
                }
                if (fi.getSize() < 1) {
                    continue;
                }
                //需要换个名字，保留后缀
                String oldName = fi.getName();
                String houzhui = oldName.substring(oldName.lastIndexOf('.'));
                String newName = UUID.randomUUID() + houzhui;
                ServletContext application = super.getServletContext();
                String path0 = application.getRealPath("img");
                File path = new File(path0);
                if (!path.exists())
                    path.mkdirs();
                fi.write(new File(path, newName));
                student.setIdcardpic("img/" + newName);
            }
            System.out.println(student + "<<<<<<<<<<<<<<<<");
            int r = StudentService.ME.update(student);
            return r > 0 ? Result.success() : Result.error("更改失败");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("更改失败:" + e);
        }

    }
    public Result updateStudent(HttpServletResponse response, HttpServletRequest request) throws ServletException,
            IOException {
        String stuno = request.getParameter("stuno");
        String sname = request.getParameter("sname");
        String sex = request.getParameter("sex");
        String telephone = request.getParameter("telephone");
        String qq = request.getParameter("QQ");
        String weChat = request.getParameter("wechat");
        String gradeID = request.getParameter("gradeid");
        Date d1 = StrUtil.toDate(request.getParameter("enterdate"));
        Date d2 = StrUtil.toDate(request.getParameter("birthday"));
        String city = request.getParameter("fromcity");
        String address = request.getParameter("address");
        String pwd = request.getParameter("password");
        String idCardPic = request.getParameter("idcardpic");

        Student student = new Student();
        student.setStuno(Long.parseLong(stuno));
        student.setSname(sname);
        student.setSex(sex);
        student.setTelephone(telephone);
        student.setQQ(qq);
        student.setWechat(weChat);
        student.setGradeid(Integer.parseInt(gradeID));
        student.setEnterdate(d1);
        student.setBirthday(d2);
        student.setFromcity(city);
        student.setAddress(address);
        student.setPassword(pwd);
        student.setIdcardpic(idCardPic);
        int r = StudentService.ME.update(student);
        if (r > 0)
            return Result.success();
        return Result.error("更新失败");
    }
    public Result addStudent(HttpServletResponse response, HttpServletRequest request) throws ServletException,
            IOException {
        String sname = request.getParameter("sname");
        String sex = request.getParameter("sex");
        String telephone = request.getParameter("telephone");
        String qq = request.getParameter("QQ");
        String weChat = request.getParameter("wechat");
        String gradeID = request.getParameter("gradeid");
        Date d1 = StrUtil.toDate(request.getParameter("enterdate"));
        Date d2 = StrUtil.toDate(request.getParameter("birthday"));
        String city = request.getParameter("fromcity");
        String address = request.getParameter("address");
        String pwd = request.getParameter("password");
        String idCardPic = request.getParameter("idcardpic");

        Student student = new Student();
        student.setSname(sname);
        student.setSex(sex);
        student.setTelephone(telephone);
        student.setQQ(qq);
        student.setWechat(weChat);
        student.setGradeid(Integer.parseInt(gradeID));
        student.setEnterdate(d1);
        student.setBirthday(d2);
        student.setFromcity(city);
        student.setAddress(address);
        student.setPassword(pwd);
        student.setIdcardpic(idCardPic);
        int r = StudentService.ME.add(student);
        if (r > 0)
            return Result.success();
        return Result.error("新增失败");
    }

    public Result checkwechat(HttpServletResponse response, HttpServletRequest request) throws ServletException,
            IOException {
        long stuno=StrUtil.toLong(request.getParameter("stuno"),-1);
        String we=request.getParameter("wechat");
        boolean i = StudentService.ME.checkWechat(we,stuno);
        return i?Result.error("这个微信号["+we+"]已经被注册了"):Result.success();
    }
    public Result findStu(HttpServletResponse response, HttpServletRequest request) throws ServletException,
            IOException {
        Long stuno = Long.parseLong(request.getParameter("stuno"));
        Student r = StudentService.ME.get(stuno);
        return r == null ? Result.error("学生不存在") : Result.success(r);
    }
    public Result batchDel(HttpServletResponse response, HttpServletRequest request) throws ServletException,
            IOException {
        String id=request.getParameter("ids");
        String []ar=id.split(",#");
        long sr[]=new long[ar.length];
        for (int i = 0; i < ar.length; i++) {
            sr[i]=Long.parseLong(ar[i]);
        }
        //delete from s_student where stuno in()
        return Result.error("学生"+id+"不存在");
    }
    //年级
    public List<Grade> findGradesALL(HttpServletResponse response, HttpServletRequest request) throws ServletException,
            IOException {
        return GradeService.ME.findAll();
    }
    public Result findGrades(HttpServletResponse response, HttpServletRequest request) throws ServletException,
            IOException {
        return Result.success(GradeService.ME.findAll());
    }
    public Result adminLogin(HttpServletResponse response, HttpServletRequest request) throws ServletException,
            IOException {
        String name=request.getParameter("name");
        String pass=request.getParameter("pass");
        String v=request.getParameter("vcode");
        System.out.println(v+"================?"+request.getSession().getAttribute("piccode"));
        if(!v.equals(request.getSession().getAttribute("piccode"))){
            return Result.error("验证码输入错误");
        }
        //db
        if(name.startsWith("java83")&&pass.equals("1234")){
            return Result.success("登录成功");
        }
        return Result.error("错误的用户名或者密码！");
    }
    public void genCode(HttpServletResponse response, HttpServletRequest request) throws ServletException,
            IOException {
        response.reset();
        //设置内容类型
        response.setContentType("image/jpeg");

        //图像数据缓冲区
        BufferedImage bi = new BufferedImage(68, 22, BufferedImage.TYPE_INT_RGB);
        //绘制图片
        Graphics g = bi.getGraphics();
        //获取颜色
        Color c = new Color(200, 150, 255);
        g.setColor(c);
        g.fillRect(0, 0, 68, 22);

        char[] ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
        //生成随机数
        Random r = new Random();
        int len = ch.length, index;
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 4; i++) {
            index = r.nextInt(len);
            g.setColor(new Color(r.nextInt(88), r.nextInt(188), r.nextInt(255)));
            g.drawString(ch[index] + "", (i * 15) + 3, 18);
            sb.append(ch[index]);
        }
        request.getSession().setAttribute("piccode", sb.toString());
        //输出图片
        //前3个，设置不缓存
        response.setHeader( "Prama", "no-cache");
        response.setHeader( "Cache-Control", "no-cache" );
        response.setDateHeader( "Expires", 0);
        ImageIO.write(bi, "JPG", response.getOutputStream());
    }
}
